package com.fjwt.gz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.core.third.bo.VirtualGoodsSupplierBo;
import com.fjwt.gz.core.third.interfaces.OutSideSupplierService;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.dto.AwardVirtualOutsideDTO;
import com.fjwt.gz.db.entity.AwardVirtualInsideEntity;
import com.fjwt.gz.db.entity.AwardVirtualOutsideEntity;
import com.fjwt.gz.db.entity.AwardVirtualSupplierEntity;
import com.fjwt.gz.db.vo.AwardVirtualOutsideVO;
import com.fjwt.gz.service.mapper.AwardVirtualOutsideMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  虚拟商品外部商品表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AwardVirtualOutsideService extends ServiceImpl<AwardVirtualOutsideMapper, AwardVirtualOutsideEntity> {


    @Autowired
    private AwardVirtualSupplierService awardVirtualSupplierService;

    @Autowired
    private AwardVirtualInsideService awardVirtualInsideService;

    /**
     * 获取商品列表
     * @param iPage 分页
     * @param virtualOutsideDTO 查询参数
     * @return
     */
    public IPage<AwardVirtualOutsideVO> queryList(IPage iPage, AwardVirtualOutsideDTO virtualOutsideDTO) {
        return baseMapper.queryList(iPage, virtualOutsideDTO);
    }


    /**
     * 刷新商品信息
     * @param virtualOutsideDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void refreshGoodsDetail(AwardVirtualOutsideDTO virtualOutsideDTO) {
        if (ObjectUtils.isEmpty(virtualOutsideDTO.getVirtualOutsideId())) {
            throw new BizException("请选择要刷新的商品");
        }
        AwardVirtualOutsideEntity awardVirtualOutside = baseMapper.selectById(virtualOutsideDTO.getVirtualOutsideId());
        if (ObjectUtils.isEmpty(awardVirtualOutside)) {
            throw new BizException("所选商品异常");
        }
        //获取对应的供应商信息
        AwardVirtualSupplierEntity supplierEntity = awardVirtualSupplierService.getById(awardVirtualOutside.getVirtualSupplierId());

        OutSideSupplierService outSideSupplierService = SpringBeansUtil.getBean(supplierEntity.getSupplierName()
                + "OutSideSupplierService", OutSideSupplierService.class);
        if (outSideSupplierService == null) {
            throw new BizException("该供应商暂不支持该功能");
        }
        JSONObject supplierConfig = awardVirtualSupplierService.getSupplierConfig(supplierEntity.getVirtualSupplierId());
        if (supplierConfig == null || !supplierConfig.containsKey("authConfig")) {
            throw new BizException("该供应商配置信息异常，请检查");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("goodsId", awardVirtualOutside.getThirdGoodsId());
        VirtualGoodsSupplierBo supplierBo = BeanUtil.copyProperties(supplierEntity, VirtualGoodsSupplierBo.class);
        supplierBo.setAuthConfig((String) supplierConfig.get("authConfig"));
        JSONObject repJson = outSideSupplierService.getGoods(jsonObject, supplierBo);

        saveList(Collections.singletonList(repJson.getJSONObject("data")), supplierEntity.getVirtualSupplierId());
    }

    /**
     * 商品订阅
     * @param virtualOutsideDTO
     */
    public void goodsSubscribe(AwardVirtualOutsideDTO virtualOutsideDTO) {
        if (ObjectUtils.isEmpty(virtualOutsideDTO.getVirtualOutsideId())) {
            throw new BizException("请选择要订阅的商品");
        }
        AwardVirtualOutsideEntity awardVirtualOutside = baseMapper.selectById(virtualOutsideDTO.getVirtualOutsideId());
        if (ObjectUtils.isEmpty(awardVirtualOutside)) {
            throw new BizException("所选商品异常");
        }
        if (1 == awardVirtualOutside.getIsSubscribe()) {
            throw new BizException("该商品已订阅，无需再次订阅");
        }
        AwardVirtualSupplierEntity supplierEntity = awardVirtualSupplierService.getById(awardVirtualOutside.getVirtualSupplierId());
        if (ObjectUtils.isEmpty(supplierEntity)) {
            throw new BizException("该商品供应商出现异常");
        }

        OutSideSupplierService outSideSupplierService = SpringBeansUtil.getBean(supplierEntity.getSupplierName()
                + "OutSideSupplierService", OutSideSupplierService.class);
        if (outSideSupplierService == null) {
            throw new BizException("该供应商暂不支持该功能");
        }
        JSONObject supplierConfig = awardVirtualSupplierService.getSupplierConfig(supplierEntity.getVirtualSupplierId());
        if (supplierConfig == null || !supplierConfig.containsKey("authConfig")) {
            throw new BizException("该供应商配置信息异常，请检查");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("goodsId", awardVirtualOutside.getThirdGoodsId());
        VirtualGoodsSupplierBo supplierBo = BeanUtil.copyProperties(supplierEntity, VirtualGoodsSupplierBo.class);
        supplierBo.setAuthConfig((String) supplierConfig.get("authConfig"));
        outSideSupplierService.goodsSubscribe(jsonObject, supplierBo);

        awardVirtualOutside.setIsSubscribe(1);
        updateById(awardVirtualOutside);
    }

    /**
     * 商品取消订阅
     * @param virtualOutsideDTO
     */
    public void goodsUnSubscribe(AwardVirtualOutsideDTO virtualOutsideDTO) {
        if (ObjectUtils.isEmpty(virtualOutsideDTO.getVirtualOutsideId())) {
            throw new BizException("请选择要取消订阅的商品");
        }
        AwardVirtualOutsideEntity awardVirtualOutside = baseMapper.selectById(virtualOutsideDTO.getVirtualOutsideId());
        if (ObjectUtils.isEmpty(awardVirtualOutside)) {
            throw new BizException("所选商品异常");
        }
        if (0 == awardVirtualOutside.getIsSubscribe()) {
            throw new BizException("该商品还未订阅，请先订阅");
        }
        AwardVirtualSupplierEntity supplierEntity = awardVirtualSupplierService.getById(awardVirtualOutside.getVirtualSupplierId());

        OutSideSupplierService outSideSupplierService = SpringBeansUtil.getBean(supplierEntity.getSupplierName()
                + "OutSideSupplierService", OutSideSupplierService.class);
        if (outSideSupplierService == null) {
            throw new BizException("该供应商暂不支持该功能");
        }
        JSONObject supplierConfig = awardVirtualSupplierService.getSupplierConfig(supplierEntity.getVirtualSupplierId());
        if (supplierConfig == null || !supplierConfig.containsKey("authConfig")) {
            throw new BizException("该供应商配置信息异常，请检查");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("goodsId", awardVirtualOutside.getThirdGoodsId());
        VirtualGoodsSupplierBo supplierBo = BeanUtil.copyProperties(supplierEntity, VirtualGoodsSupplierBo.class);
        supplierBo.setAuthConfig((String) supplierConfig.get("authConfig"));
        outSideSupplierService.goodsUnSubscribe(jsonObject, supplierBo);

        awardVirtualOutside.setIsSubscribe(0);
        updateById(awardVirtualOutside);
    }


    /**
     * 循环插入或修改数据库
     * @param data
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveList(List<JSONObject> data, Long supplierId) {
        List<String> goodsIds = data.stream().map(item -> item.getString("goodsid")).collect(Collectors.toList());
        LambdaQueryWrapper<AwardVirtualOutsideEntity> gw = AwardVirtualOutsideEntity.gw()
                .in(AwardVirtualOutsideEntity::getThirdGoodsId, goodsIds)
                .eq(AwardVirtualOutsideEntity::getVirtualSupplierId, supplierId);
        List<AwardVirtualOutsideEntity> awardVirtualOutsideList = baseMapper.selectList(gw);
        Map<String, AwardVirtualOutsideEntity> outsideEntityMap = awardVirtualOutsideList.stream()
                .collect(Collectors.toMap(AwardVirtualOutsideEntity::getThirdGoodsId, Function.identity()));

        List<AwardVirtualOutsideEntity> saveOrUpdateList = new ArrayList<>();
        for (JSONObject jsonObject : data) {
            String goodsId = jsonObject.getString("goodsid");
            String goodsName = jsonObject.getString("goodsname");
            String imgUrl = "//images.weserv.nl/?url=" + jsonObject.getString("imgurl");
            String attach = jsonObject.getString("attach");
            Integer goodsPrice = jsonObject.getBigDecimal("goodsprice").multiply(new BigDecimal("100")).intValue();
            Integer marketPrice = jsonObject.getBigDecimal("marketprice").multiply(new BigDecimal("100")).intValue();
            Integer goodsType = jsonObject.getInteger("goodstype");
            Integer goodsStatus = jsonObject.getInteger("goodsstatus");
            if (outsideEntityMap.containsKey(goodsId)) {
                AwardVirtualOutsideEntity awardVirtualOutsideEntity = outsideEntityMap.get(goodsId);
                awardVirtualOutsideEntity.setGoodsName(goodsName)
                        .setGoodsImg(imgUrl)
                        .setGoodsDetail(attach)
                        .setGoodsPrice(goodsPrice)
                        .setMarketPrice(marketPrice)
                        .setType(goodsType)
                        .setState(goodsStatus)
                        .setOriginalInfo(jsonObject.toJSONString());
                saveOrUpdateList.add(awardVirtualOutsideEntity);
//                baseMapper.updateById(awardVirtualOutsideEntity);
            }else {
                AwardVirtualOutsideEntity awardVirtualOutside = new AwardVirtualOutsideEntity();
                awardVirtualOutside.setThirdGoodsId(goodsId)
                        .setGoodsName(goodsName)
                        .setGoodsImg(imgUrl)
                        .setGoodsDetail(attach)
                        .setGoodsPrice(goodsPrice)
                        .setMarketPrice(marketPrice)
                        .setType(goodsType)
                        .setState(goodsStatus)
                        .setOriginalInfo(jsonObject.toJSONString())
                        .setVirtualSupplierId(supplierId);
                saveOrUpdateList.add(awardVirtualOutside);
//                baseMapper.insert(awardVirtualOutside);
            }
        }
        saveOrUpdateBatch(saveOrUpdateList);
    }

    /**
     * 外部商品转内部商品
     * @param virtualOutsideDTO
     */
    public void outsideToInsideGoods(AwardVirtualOutsideDTO virtualOutsideDTO, Long sysUserId) {
        if (virtualOutsideDTO.getVirtualOutsideId() == null) {
            throw new BizException("请求参数不全，请检查！");
        }
        if (virtualOutsideDTO.getGoodsPrice() > virtualOutsideDTO.getMarketPrice()) {
            throw new BizException("商品进价不能大于市场价，请重新输入！");
        }
        //通过机构号和外部商品id查询内部商品
        LambdaQueryWrapper<AwardVirtualInsideEntity> gw = AwardVirtualInsideEntity.gw();
        gw.eq(AwardVirtualInsideEntity::getVirtualOutsideId, virtualOutsideDTO.getVirtualOutsideId());
        AwardVirtualInsideEntity virtualInsideEntity = awardVirtualInsideService.getOne(gw);
        if (virtualInsideEntity != null) {
            throw new BizException("该商品已存在，请勿重复添加！");
        }
        virtualInsideEntity = new AwardVirtualInsideEntity();
        virtualInsideEntity.setVirtualOutsideId(virtualOutsideDTO.getVirtualOutsideId())
                .setGoodsName(virtualOutsideDTO.getGoodsName())
                .setGoodsDetail(virtualOutsideDTO.getGoodsDetail())
                .setGoodsPrice(virtualOutsideDTO.getGoodsPrice())
                .setMarketPrice(virtualOutsideDTO.getMarketPrice())
                .setGoodsImgListBig(virtualOutsideDTO.getGoodsImg())
                .setType(virtualOutsideDTO.getType())
                .setRemark(virtualOutsideDTO.getRemark())
                .setCreatedUid(sysUserId);
        awardVirtualInsideService.save(virtualInsideEntity);
    }

    /**
     * 外部商品批量转内部商品
     * @param virtualOutsideIds
     */
    public void outsideToInsideGoodsBatch(String virtualOutsideIds, Long sysUserId) {
        if (StringUtils.isBlank(virtualOutsideIds)) {
            throw new BizException("请求参数不全，请检查！");
        }
        String[] outsideGoodsIdStr = virtualOutsideIds.split(",");
        //批量查询
        List<AwardVirtualOutsideEntity> virtualOutsideList = this.listByIds(Arrays.asList(outsideGoodsIdStr));
        if (virtualOutsideList == null) {
            throw new BizException("未查询到外部商品！");
        }
        List<AwardVirtualInsideEntity> insideEntityList = new ArrayList<>();

        virtualOutsideList.forEach(virtualOutside -> {
            AwardVirtualInsideEntity virtualInsideEntity = new AwardVirtualInsideEntity();
            virtualInsideEntity.setVirtualOutsideId(virtualOutside.getVirtualOutsideId())
                    .setGoodsName(virtualOutside.getGoodsName())
                    .setGoodsDetail(virtualOutside.getGoodsDetail())
                    .setGoodsPrice(virtualOutside.getGoodsPrice())
                    .setMarketPrice(virtualOutside.getMarketPrice())
                    .setType(virtualOutside.getType())
                    .setRemark(virtualOutside.getRemark())
                    .setCreatedUid(sysUserId);
            insideEntityList.add(virtualInsideEntity);
        });
        awardVirtualInsideService.saveBatch(insideEntityList);
    }
}
